package com.srwl.mytx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.OrderService;
import com.srwl.mytx.utils.Utils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderSendActivity extends BaseActivity {
    private static final String TAG = "OrderSendActivity";

    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_topic_title)
    TextView tv_topicTitle;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_order_id)
    TextView tv_orderId;
    @BindView(R.id.btn_pay_order)
    Button btn_commit;
    @BindView(R.id.tv_order_status)
    TextView tv_orderStatus;
    @BindView(R.id.tv_send_status)
    TextView tv_sendStatus;
    @BindView(R.id.spinner)
    AppCompatSpinner spinner;
    @BindView(R.id.rl_spinner)
    RelativeLayout rl_spinner;
    @BindView(R.id.et_express)
    EditText et_express;
    @BindView(R.id.et_phone)
    TextView et_phone;
    @BindView(R.id.et_contact)
    EditText et_contact;
    @BindView(R.id.et_address)
    EditText et_address;
    @BindView(R.id.rl_send_status)
    RelativeLayout rl_sendStatus;
    private Orders order;
    private Topic topic;
    private boolean isSent;
    private String selectExpress;
    private String expressId;
    private boolean isSeller;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_send);
        ButterKnife.bind(this);
        toolbar.setNavigationOnClickListener(v -> finish());
        order = getIntent().getParcelableExtra(Constant.EXTRA_INFO_ORDER);
        topic = order.getTopic();
        if (order == null) {
            throw new RuntimeException("order can't empty");
        }

        setViewAndEvent();
    }

    private void setViewAndEvent() {

        tv_topicTitle.setText(order.getTitle());
        tv_amount.setText(Utils.moneyFormat(order.getAmount()));
        //发货标记
        isSent = Constant.ORDER_SEND_STATUS_SENT == order.getSendStatus();
        isSeller = UserProfileManager.getInstance().getLoginUserInfo().getuId().equals(order.getSellerId());
        showSpinner();
        switch (order.getStatus()) {

            case Constant.ORDER_STATUS_PAID:
                tv_orderStatus.setText("待发货");
                rl_sendStatus.setVisibility(View.GONE);
                btn_commit.setOnClickListener(v -> prepareOrderSend());
                break;
            case Constant.ORDER_STATUS_SENT:
                tv_orderStatus.setText("已发货");
                rl_sendStatus.setVisibility(View.GONE);
                if (isSeller) {
                    btn_commit.setText("修改发货信息");
                    et_express.clearFocus();
                    btn_commit.setOnClickListener(v -> prepareOrderSend());
                } else {
                    et_express.setFocusable(false);
                    spinner.setEnabled(false);
                    btn_commit.setVisibility(View.GONE);
                }
                break;

            case Constant.ORDER_STATUS_REFUNDING:
                tv_orderStatus.setText("退款中...");
                showOrderSendStatus();
                if (isSeller) {
                    btn_commit.setOnClickListener(v -> prepareOrderSend());
                } else {
                    et_express.setFocusable(false);
                    spinner.setEnabled(false);
                }
                break;
            case Constant.ORDER_STATUS_REFUSE_REFUND:
                tv_orderStatus.setText("卖家拒绝退款");
                showOrderSendStatus();
                if (isSeller) {
                    btn_commit.setOnClickListener(v -> prepareOrderSend());
                }
                break;

        }
        if (order.getExpressId() != null) {
            et_express.setText(order.getExpressId());
        }

        tv_orderId.setText(order.getId());
        et_contact.setFocusable(false);
        et_phone.setFocusable(false);
        et_address.setFocusable(false);
        et_contact.setText(order.getContact());
        et_phone.setText(order.getPhone());
        et_address.setText(order.getAddress());


    }

    private void showOrderSendStatus() {
        if (isSent) {
            tv_sendStatus.setText("已发货");
        } else {
            tv_sendStatus.setText("未发货");
        }
    }

    private void showSpinner() {
        ArrayList<String> expressList = new ArrayList<String>();
        if (isSeller) {
            expressList.add("顺丰快递");
            expressList.add("中通快递");
            expressList.add("圆通快递");
            expressList.add("韵达快递");
            expressList.add("宅急送");
            expressList.add("天天快递");
            expressList.add("申通快递");
            expressList.add("汇通快递");
        } else {
            expressList.add(order.getExpressName());
        }
        ArrayAdapter<String> arr_adapter = new ArrayAdapter(this, R.layout.custom_spinner_item, expressList);
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arr_adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                TextView tv=(TextView)parent;
//                tv.setTextColor(getResources().getColor(R.color.blue));

                selectExpress = expressList.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

//        String expressName = order.getExpressName();
//        if (expressName != null) {
//
//            for (int i = 0; i < expressList.size(); i++) {
//                String s = expressList.get(i);
//                if (expressName.equals(s)) {
//                    spinner.setSelection(i);
//                }
//            }
//
//        }

    }

    private void syncOrderData(String orderId) {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .syncOrderData(orderId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 同步订单信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        order = body.toJavaObject(Orders.class);
                        order.setTopic(topic);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    private void prepareOrderSend() {

        if (selectExpress == null) {
            showToast(btn_commit, "请选择快递名称");
            return;
        }

        expressId = et_express.getText().toString();
        if (TextUtils.isEmpty(expressId)) {
            showToast(btn_commit, "请输入快递单号");
            return;
        }
        Orders updateOrder = new Orders();
        updateOrder.setId(order.getId());
        updateOrder.setExpressId(expressId);
        updateOrder.setExpressName(selectExpress);
        if (isSent) {
            modifyOrderSendInfo(updateOrder);
        } else {
            orderSend(updateOrder);
        }
    }

    private void modifyOrderSendInfo(Orders updateOrder) {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .modifyOrderSendInfo(updateOrder)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        Log.d(TAG, "onResponse: 修改订单发货信息完成");
                        showToast(btn_commit, "修改订单发货信息完成");
                        order.setExpressName(selectExpress);
                        order.setExpressId(expressId);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });

    }

    private void orderSend(Orders updateOrder) {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(OrderService.class)
                .orderSend(updateOrder)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        Log.d(TAG, "onResponse: 发货完成");
                        showToast(btn_commit, "发货完成");
                        order.setStatus(Constant.ORDER_SEND_STATUS_SENT);
                        order.setExpressName(selectExpress);
                        order.setExpressId(expressId);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_ORDER, order));
                        setViewAndEvent();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }


}
